package com.gzedu.frame.db;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;

import android.content.Context;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;

import com.gzedu.frame.bean.FrameSettingSingleton;
import com.gzedu.frame.logic.net.xml.XMLParser;
import com.gzedu.frame.util.file.AssetsTool;

/**
 * 
 * <font color="#0000FF">
 * <p>
 * 此类主要处理数据的CURD以及数据库信息的初始化
 * </p>
 * </font>
 * 
 * @Package com.gzedu.frame.db
 * @company: 广州远程教育中心有限公司
 * @author : 戴俊林
 * @date 2012-8-29 下午4:18:12
 * @version V1.0
 */
public class BaseDbDao extends BaseDateBase {
	
	private static FrameSettingSingleton frameSetting;

	private BaseDateBase dbHelp = null;
	private static BaseDbDao baseDbDao;

	private static Map<String, String> dbMap = null;
	private static List<Map<String, String>> tableList = null;

	private static Context context;
	
	private static int version ;
	private static String dbName ;

	/**
	 * 
	 * @param context
	 */
	private BaseDbDao(Context _context) {
		super(_context, dbName,tableList,version);
		if (dbHelp == null) {
			dbHelp = new BaseDateBase(_context, dbName,tableList,version);
		}
	}

	/**
	 * 
	*<p>获取对象实例</p>
	* @param @param _context
	* @param @return    
	* @return BaseDbDao    
	* @throws
	 */
	public static BaseDbDao getInstance(Context _context) {
		if (baseDbDao == null) {
			context = _context;
			initDbInfo();
			baseDbDao = new BaseDbDao(_context);
		}
		return baseDbDao;
	}

	/**
	 * 
	*<p>初始化数据库信息</p>
	*<p>1、获取数据库名及描述</p>
	*<p>2、获取数据库创建表和删除表的DLL语句</p>
	* @param     
	* @return void    
	* @throws
	 */
	@SuppressWarnings("unchecked")
	public static void initDbInfo() {
		frameSetting=FrameSettingSingleton.getInstance();
		dbMap = new HashMap<String, String>();
		tableList = new ArrayList<Map<String, String>>();
		XMLParser xmltool = new XMLParser();
		Map<String, Object> map = xmltool.parserXML(AssetsTool
				.getAssets(context, "DB.xml"));
		String key = map.keySet().iterator().next();
		List<Map<String, Object>> dbInfoList = (List<Map<String, Object>>) map
				.get(key);
		for (Map<String, Object> dbInfoMap : dbInfoList) {
			Iterator<String> dbInfoIterator = dbInfoMap.keySet().iterator();
			while (dbInfoIterator.hasNext()) {
				String dbInfoKey = dbInfoIterator.next();
				Object obj = dbInfoMap.get(dbInfoKey);
				if (obj instanceof String) {
					dbMap.put(dbInfoKey, (String) obj);
				} else if (obj instanceof List) {
					List<Map<String, String>> tableInfoList = (List<Map<String, String>>) obj;
					for (Map<String, String> tableInfoMap : tableInfoList) {
						Iterator<String> iterator = tableInfoMap.keySet()
								.iterator();
						Map<String, String> tableMap = new HashMap<String, String>();
						while (iterator.hasNext()) {
							String tablekey = iterator.next();
							String value = tableInfoMap.get(tablekey);
							tableMap.put(tablekey, value);
						}
						tableList.add(tableMap);
					}
				}
			}
		}
		frameSetting.setDB_LocalPath(dbMap.get("DB_LocalPath"));
		frameSetting.setDB_Version(dbMap.get("DB_Version"));
		version=Integer.parseInt(dbMap.get("DB_Version"));
		dbName=dbMap.get("DB_Name");
	}

	/**
	 * 
	*<p>此方法可用于数据库的增，删，改</p>
	* @param @param sql
	* @param @return    
	* @return boolean    
	* @throws
	 */
	@SuppressWarnings("finally")
	public boolean execute(String sql) {
		boolean isSuccess = false;
		SQLiteDatabase db = this.getWritableDatabase();
		db.beginTransaction();
		try {
			db.execSQL(sql);
			db.setTransactionSuccessful();
			isSuccess = true;
		} finally {
			db.endTransaction();
			return isSuccess;
		}
	}

	/**
	 * 
	*<p>此方法可用于批量数据库的插入数据</p>
	*<p>此方法会自动对SQL进行处理</p>
	*<p>此处是批量插入N条数据的SQL，与插入单条数据的SQL是不一样的。</p>
	*<font color="##FF0000">
	*<p>注意事项:</p>
	*<p>例如:INSERT INTO TBL_STUDENT (STUDENT_ID,STUDENTNAME,STUDENTAGE)	SELECT	?,?,? ;</p>
	*<p>与其他数据库的SQL语言有点不一样。在插入时并没有采用values 而是使用SELECT</p>
	*<p>因为插入数据的SQL数据必须是按顺序排列的。所以此处的Map必须为线性LinkedHashMap</p>
	* </font>
	* @param @param sql		带占位符的SQL
	* @param @param list	插入的数据
	* @param @return    
	* @return boolean		是否正确
	* @throws
	* @see {@link #AssemblySql}
	 */
	@SuppressWarnings("finally")
	public boolean insert(String sql, List<Map<String, String>> list) {
		boolean isSuccess = false;
		SQLiteDatabase db = this.getWritableDatabase();
		db.beginTransaction();
		try {
			sql = AssemblySql.assemblySqlByList(list, sql);
			db.execSQL(sql);
			db.setTransactionSuccessful();
			isSuccess = true;
		} finally {
			db.endTransaction();
			return isSuccess;
		}
	}

	/**
	 * 
	*<p>获取查询数据</p>
	*<p>可用于模糊查询和指定查询</p>
	*<p>因为是同一的查询工具，在查询的数据结果，字段一律按照全部小写处理。</p>
	*<p>返回数据Map中的KEY 均为数据库表字段名的小写名称</p>
	* @param @param sql		带占位符的SQL
	* @param @param object	插入的数据
	* @param @return    
	* @return List<Map<String,String>>    
	* @throws
	 */
	@SuppressWarnings("finally")
	public List<Map<String, String>> query(String sql, String[] object) {
		List<Map<String, String>> list = null;
		SQLiteDatabase db = this.getWritableDatabase();
		db.beginTransaction();
		try {
			Cursor cursor = db.rawQuery(sql, object);
			if (cursor != null) {
				list = new ArrayList<Map<String, String>>();
				while (cursor.moveToNext()) {
					Map<String, String> map = new HashMap<String, String>();
					int count = cursor.getColumnCount();
					for (int i = 0; i < count; i++) {
						map.put(cursor.getColumnName(i).toLowerCase(), cursor.getString(i));
					}
					list.add(map);
				}
			}
			cursor.close();
			db.setTransactionSuccessful();
		} finally {
			db.endTransaction();
			return list;
		}
	}

}
